import re
from django.contrib.auth.backends import ModelBackend
from itsdangerous import BadData

from apps.users.models import User
from meiduo_mall import settings


def abc(username):
    try:
        if re.match(r'1[3-9]\d{9}', username):
            user = User.objects.get(mobile=username)

        else:

            user = User.objects.get(username=username)


    except User.DoesNotExist:

        return None

    return user

class UsernameMoblieModelBackend(ModelBackend):


    def authenticate(self, request, username=None, password=None, **kwargs):


        # try:
        #     if re.match(r'1[3-9]\d{9}',username):
        #         user = User.objects.get(mobile=username)
        #
        #     else:
        #
        #         user = User.objects.get(username=username)
        #
        #
        # except User.DoesNotExist:
        #
        #     return None
        user= abc(username)
        if user is not None and user.check_password(password):

            return user

from itsdangerous import TimedJSONWebSignatureSerializer as Serializer


def generic_verify_email_url(user_id):
    s = Serializer(secret_key=settings.SECRET_KEY,expires_in=3600)
    data = {
        'user_id':user_id
    }
    token = s.dumps(data)
    return settings.EMAIL_VERIFY_URL+'?token=' + token.decode()

def check_verify_email_token(token):
    s = Serializer(secret_key=settings.SECRET_KEY, expires_in=3600)
    try:
        result = s.loads(token)
    except BadData:
        return None
    return result.get('user_id')



